import React, { Component } from 'react';
import config from './config';
import { getMultiLang, createPage, cardCache, toast } from 'nc-lightapp-front';
import api from '../../common/api';
import {
    onSearchAfterEvent,
    onSearchButtonClick,
    onBackButtonClick,
    onTableRowDoubleClick,
    onTablePageChange,
    onTableButtonClick
} from './events';

const { setDefData, getDefData } = cardCache;

class Page extends Component {
    constructor(props) {
        super(props);
        props.use.search(config.headcode);
        props.use.table(config.bodycode);
        // this.state = {
        //     multilang: {}
        // };
        this.initTempAndLang();
    }

    initTempAndLang() {
        const props = this.props;
        // getMultiLang({
        //     ...config.multilang,
        //     callback: (json) => {
        //         this.setState({ multilang: json }, () => {
        //         });
        //     }
        // });
        props.createUIDom({ pagecode: config.pagecode }, (data) => {
            console.log('=====template', data);
            this.setButton(data.button);
            this.setMeta(data.template);
        });
    }

    setMeta(meta) {
        const props = this.props;
        // const { setPageStatus } = this.props;
        // meta[config.bodycode].status = 'browse';
        setDefData(`${config.headcode}_oid`, config.datasource, meta[config.headcode].oid);

        meta[config.headcode].items.forEach((item) => {
            if (!item.visible) return;
            if (item.attrcode === 'deptid') {
                item.queryCondition = () => {
                    return {
                        pk_org: getDefData('pk_org', config.datasourceCommon),
                        TreeRefActionExt: 'nccloud.web.erm.action.ref.sqlbuilder.DeptTreeGridRef',
                        DataPowerOperationCode: 'fi',
                        isDataPowerEnable: 'Y'
                    };
                };
            } else if (item.attrcode === 'pk_tradetypeid') {
                item.queryCondition = () => {
                    return {
                        GridRefActionExt: 'nccloud.web.erm.action.ref.sqlbuilder.BxTranstypeRefSqlBuilder'
                    };
                };
            } else if (item.attrcode === 'jkbxr') {
                item.queryCondition = () => {
                    return {
                        pk_org: getDefData('pk_org', config.datasourceCommon),
                        GridRefActionExt: 'nccloud.web.erm.action.ref.sqlbuilder.PsndocTreeGridRef',
                        DataPowerOperationCode: 'fi',
                        isDataPowerEnable: 'Y'
                    };
                };
            }
        });

        meta[config.bodycode].items.push({
            label: props.multilang['opr_title'],
            itemtype: 'customer',
            attrcode: 'opr',
            width: '140px',
            visible: true,
            fixed: 'right',
            render: (text, record, index) => {
                return props.button.createOprationButton(['table_create'], {
                    area: config.innerButtonArea,
                    buttonLimit: 3,
                    onButtonClick: (props, key) => onTableButtonClick.call(this, props, key, text, record, index)
                });
            }
        });

        props.meta.setMeta(meta, () => {
            this.initPage();
        });
    }

    setButton(button) {
        const props = this.props;

        props.button.setButtons(button);
        props.button.setPopContent(['del'], '确认要执行该操作吗？');
    }

    initPage() {
        const props = this.props;
        const searchVal = getDefData(config.searchCache, config.datasource);
        if (!getDefData('pk_org', config.datasourceCommon)) {
            api.getUserInfo().then((data) => {
                setDefData('pk_org', config.datasourceCommon, data.pk_org);
                setDefData('pk_org', config.datasourceCommon, data.pk_org);
            });
        }
        if (searchVal && searchVal.conditions) {
            this.props.search.setSearchValue(config.headcode, searchVal);
            this.loadData();
        }
        this.setPageStatus();
    }

    setPageStatus() {
        // TODO 清理选择状态、根据选择判断
        // this.props.button.setButtonDisabled(['edit', 'del'], true);
    }

    loadData() {
        const props = this.props;
        const pageInfo = props.table.getTablePageInfo(config.headcode);
        const querycondition = getDefData(config.searchCache, config.datasource);
        const oid = getDefData(`${config.headcode}_oid`, config.datasource);

        const params = {
            oid,
            pageInfo,
            querycondition,
            appcode: config.appcode,
            queryAreaCode: config.headcode,
            pagecode: config.pagecode,
            querytype: 'tree'
        };

        return api.getReimbursementList(params).then((data) => {
            // 按钮初始化
            if (!data) {
                toast({
                    color: 'warning',
                    content: props.multilang['query_none_message']
                }); /* 国际化处理： 未查询出符合条件的数据*/
                props.table.setAllTableData(config.bodycode, { rows: [] });
                return;
            }

            toast({
                color: 'success',
                content: props.multilang['query_total_message'].replace('$_$', data[config.bodycode].rows.length)
            }); /* 国际化处理： 查询成功，共,条*/

            this.setData(data);
        });
    }

    setData(data) {
        const props = this.props;
        props.table.setAllTableData(config.bodycode, data[config.bodycode]);
        // TODO 处理按钮的状态
    }

    render() {
        const { table, button, search, modal, BillHeadInfo } = this.props;
        const { NCCreateSearch } = search;
        const { createModal } = modal;
        const { createBillHeadInfo } = BillHeadInfo;
        const { createSimpleTable } = table;

        return (
            <div className='nc-single-table'>
                <div className='nc-singleTable-search-area'>
                    {NCCreateSearch(config.headcode, {
                        clickSearchBtn: onSearchButtonClick.bind(this),
                        onAfterEvent: onSearchAfterEvent.bind(this)
                    })}
                </div>
                <div className='nc-singleTable-table-area'>
                    {createSimpleTable(config.bodycode, {
                        handlePageInfoChange: onTablePageChange.bind(this),
                        onRowDoubleClick: onTableRowDoubleClick.bind(this),
                        dataSource: config.datasource,
                        showIndex: true,
                        showCheck: false
                    })}
                </div>
            </div>
        );
    }
}

export default createPage({
    mutiLangCode: config.mutiLangCode,
    initTemplate: null
})(Page);
